<template>
	<view class="login-container">
		<view class="head-container">
			<van-image width="80" height="80" round
				src="https://maywork.oss-cn-shanghai.aliyuncs.com/static/runIcon.png" />
			<view class="title">五月线上系列活动</view>
		</view>
		<view class="submit-view">
			<van-button class="submit-btn" color="#e9412c" open-type="getPhoneNumber"
				@getphonenumber="handleGetPhoneNumber" block>一键登录账号</van-button>

			<van-button class="submit-btn no-login"  @click="submitLogin" block>暂不登录</van-button>
		</view>
	</view>

</template>
<script>
	import {
		WXBizDataCrypt
	} from '../../utils/WXBizDataCrypt.ts';
	import config from '../../utils/config.js'
	import moment from 'moment';
	import {
		getUserLevel,
		getWorkChart
	} from '../../common/activity.js'
	export default {
		data() {
			return {
				//昵称
				nickname: "",
				// 头像
				img: "",
				//手机号
				phone: "",
				//openid
				userToken: ""
			}
		},
		async created() {
			console.log("跳转登录了====")
			await this.getUserInfoByCode();
		},
		mounted() {},
		methods: {
			//获取手机号
			async handleGetPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					// 会话检查
					await this.checkSession()

					//手机号解密
					const code = e.detail.code
					const encryptedData = e.detail.encryptedData
					const iv = e.detail.iv
					let memberInfo = uni.getStorageSync("memberInfo")
					const sessionKey = memberInfo.sessionKey
					const appId = config.appId
					var wxBizDataCrypt = new WXBizDataCrypt(appId,
						sessionKey);
					const decryptedData = wxBizDataCrypt.decryptData(
						encryptedData, iv);
					//手机号码
					this.phone = decryptedData.phoneNumber

					this.submitLogin()

				}
			},
			checkSession() {
				return new Promise((resolve, reject) => {
					uni.checkSession({
						success: async (res) => {
							console.log("检查session 成功", res)
							resolve(res)
						},
						fail: async (err) => {
							console.log("检查session 失败", err)
							await this.getUserInfoByCode()
							resolve({
								errMsg: "checkSession:ok"
							})
						}
					})
				})

			},
			//根据code 获取用户信息
			getUserInfoByCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success: async (res) => {
							const userData = await this.$request({
								method: "POST",
								header: {
									"Content-Type": "application/json"
								},
								data: {
									"jsCode": res.code
								},
								url: '/wx/getOpenInfo'
							})
							let memberInfo = uni.getStorageSync("memberInfo") || {};
							Object.assign(memberInfo, userData.data)
							if (!memberInfo.phone) {
								//需要登录
								uni.setStorageSync("isLogin", false)
								this.isLogin = false
							} else {
								uni.setStorageSync("isLogin", true)
								this.isLogin = true
							}
							uni.setStorageSync("memberInfo", memberInfo);
							resolve(memberInfo)
						},
						fail: reject
					})
				})
			},
			// 登录前检查
			preLoginCheck() {
				if (!this.img) {
					uni.showToast({
						title: '请设置头像',
						icon: 'none'
					})
					return false
				}
				if (!this.checkNickName()) {
					return false
				}

				if (!this.checkPhone()) {
					return false
				}
				return true
			},
			//登录
			async submitLogin() {
				// if(!this.preLoginCheck()){
				// 	return
				// }
				let memberInfo = uni.getStorageSync("memberInfo") || {}
				// memberInfo.nickname = this.nickname
				// memberInfo.img = this.img
				if (this.phone) {
					memberInfo.phone = this.phone
					// 用户信息保存
					await this.$request({
						method: "POST",
						header: {
							"Content-Type": "application/json"
						},
						data: {
							...memberInfo
						},
						url: '/wx/add'
					})
					//设置会话信息
					uni.setStorageSync("memberInfo", memberInfo)
					uni.setStorageSync("isLogin", true)
				}
				//跳转首页
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			//手机号校验
			checkPhone() {
				if (!this.phone) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					})
					return false
				}
				const regex = /^1[3-9]\d{9}$/;
				if (!regex.test(this.phone)) {
					uni.showToast({
						title: '手机号格式不正确',
						icon: 'none'
					})
					return false
				}
				return true
			},
			getPhone(e) {
				console.log("getPhone", e.detail)
				this.phone = e.detail
			},
			//设置昵称
			getNickname(e) {
				console.log("getNickname", e.detail)
				this.nickname = e.detail
			},
			//timestamp格式化日期
			formatDate(timestamp) {
				return moment(timestamp * 1000).format('YYYY-MM-DD');
			},
			// 校验昵称
			checkNickName() {
				if (!this.nickname) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					})
					return false
				}
				let str = this.nickname.trim();
				if (str.length == 0) {
					uni.showToast({
						title: '请输入正确的昵称',
						icon: 'none'
					})
					return false
				}
				this.nickname = str
				if ((/[^/a-zA-Z0-9\u4E00-\u9FA5]/g).test(str)) {
					uni.showToast({
						title: '请输入中英文和数字',
						icon: 'none'
					})
					return false
				}
				return true
			},
			onChooseAvatar(e) {
				// 上传头像
				wx.uploadFile({
					url: config.apiUrl + 'common/uploadFileOss', // 你自己本地上传图片的 完整 路径
					filePath: e.detail.avatarUrl,
					name: 'file', // 文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
					success: (res) => {
						this.img = res.data
					}
				})
			},
			submit() {
				console.log("submit提交", this.nickName, this.avatarUrl)
				if (!this.avatarUrl) {
					uni.showToast({
						title: '请上传头像',
						icon: 'none'
					})
					return
				}
				if (!this.checkNickName()) {
					return
				}
				let params = {
					nickName: this.nickName,
					headImage: this.avatarUrl,
					memberId: this.userInfo.id,
				}
				console.log("params====", params)
				// return

				uni.showLoading({
					title: '加载中',
					mask: true
				})

			},
		}
	}
</script>
<style lang='scss'>
	.login-container {
		maring: 0;
		width: 100%;
		height: 100vh;
		background: #f2f4f7;

		.head-container {
			height: 540rpx;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.avatar-wrapper {
				width: 80px;
				height: 80px;
				padding: 0 !important;
				margin: 0 !important;
				border-radius: 80px;
			}

			.title {
				font-weight: bold;
				font-size: 20px;
				margin-top: 40rpx;
			}
		}

		.submit-view {
			margin-top: 180rpx;
			display: flex;
			flex-direction: column;
			width: 100%;
			align-items: center;
			justify-content: center;

			.submit-btn {
				width: 80%;
			}
			.no-login{
				margin-top:40rpx;
			}
			
			.van-button{
				font-weight: 630;
				color: #e9412c;
				background: rgba(233, 65, 44, 0.1);
				border-color: rgba(233, 65, 44, 0.1);
			}
		}
	}
</style>